/****************
 *@description: 
 *@author: Xhd
 *@date: 2023-07-21 11:35:47
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import { Form, Input, Select, Space, Button, message, Tag, Modal, Row, Col, InputNumber, Table } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import TheButton from "@/components/TheButton";
import GoBack from '@/components/TheGoBack';
import { apiStockSupplierManageList, apiStockLibraryManageList } from '@/request/procurement/store.js';
import { apiStockInLibraryAdd, apiStockInLibraryView, apiStockInLibraryDetailsAdd, apiStockInLibraryDetailsRevokeDetail, apiStockInLibraryDetailsRevokeConfirmInLibrary, apiPostChangeRemark } from '@/request/procurement/putIn.js';
import { apiGetGoodsList, apiGetGoodsDetail } from '@/request/marketingTool';
import { apiPrintInLibraryOrder } from '@/request/procurement';
import { exportSheetTable } from '@/utils/exportTable.js';
import { toPrintTool } from '@/utils/toPrint';
import store from "@/store/store";

const { Option } = Select
const { TextArea } = Input
const { Search } = Input

export default class OutPutAdd extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef()
    this.addFormRef = React.createRef()
    this.state = {
      searchDataSource: [],
      columns: [
        {
          title: "序号",
          width: 50,
          dataIndex: "index",
          align: "center",
          key: "index",
          width: 120,
          render: (_text, _record, index) => {
            return ((this.state.pageData.pageNo - 1) * (this.state.pageData.pageSize) + (index + 1));
          }
        },
        {
          title: "商品名称",
          dataIndex: "goodsName",
          key: "goodsName",
          align: "center",
        },
        {
          title: '物料名称',
          dataIndex: "materialName",
          key: "materialName",
          align: "center",
          width: 120,
        },
        {
          title: "规格",
          dataIndex: "goodsSkuName",
          key: "goodsSkuName",
          align: "center",
        },
        {
          title: "物料ID",
          dataIndex: "goodsSkuNo",
          key: "goodsSkuNo",
          align: "center",
        },
        {
          title: "入库前库存",
          dataIndex: "beforeCount",
          key: "beforeCount",
          width: 100,
          align: "center",
        },
        {
          title: "入库数量",
          dataIndex: "count",
          key: "count",
          width: 100,
          align: "center",
        },
        // {
        //     title: '入库价格',
        //     dataIndex: "unitPrice",
        //     key: "unitPrice",
        //     render: (text) => {
        //         return (text / 100).toFixed(2)
        //     }
        // },
        {
          title: "操作时间",
          dataIndex: "createTime",
          key: "createTime",
          align: "center",
        },
        {
          title: "操作人",
          dataIndex: "memberName",
          key: "memberName",
          align: "center",
        },
        {
          title: "操作",
          align: "center",
          render: (_text, render, index) => {
            return <div>
              <TheButton haspermi={['storage:putIn:delInfo']} onClick={() => this.del(render, index)}>删除</TheButton>
            </div>
          }
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      isModalVisible: false,
      loading: false,
      isSave: false,
      id: null,
      storeList: [],
      supplierList: [],
      code: '',
      libraryId: '',
      inLibraryId: '',
      dataId: '',
      productSku: [],
      currentSku: [],
      goodsList: [],
      materialId: '',
      options: [
        { label: '采购入库单转入库单', value: 1 },
        { label: '商城退货退款入库单', value: 2 },
        { label: '门店退货退款入库单', value: 3 },
        { label: '门店收银台退货', value: 4 },
        { label: '手动创建入库单', value: 5 },
        { label: '调拨入库单', value: 6 },
      ],
      details: [],
      status: null,
      dataType: null,
      isAdd: false
    }
  }
  componentDidMount() {
    this.setState({
      id: this.props.match.params.id
    }, async () => {
      let res1 = await this.getStores()
      if (!res1.data || res1.data.length === 0) {
        store.dispatch({
          type: 'SavePageTabValue',
          data: {
            tab: 'store'
          }
        })
        Modal.warning({
          title: '提示',
          content: '尚未创建仓库，是否立即添加仓库？',
          okText: '去添加',
          onOk: () => {
            this.props.history.push('/storageManager/store?')
          }
        });
        return
      }
      let res2 = await this.getSuppliers()
      if (!res2.data || res2.data.length === 0) {
        store.dispatch({
          type: 'SavePageTabValue',
          data: {
            tab: 'provide'
          }
        })
        Modal.warning({
          title: '提示',
          content: '尚未创建供应商，是否立即添加供应商？',
          okText: '去添加',
          onOk: () => {
            this.props.history.push('/storageManager/store')
          }
        });
        return
      }
      if (this.state.id !== 'null') {
        this.getView()
      } else {
        this.FormRef.current.setFieldsValue({
          libraryId: this.state.storeList[0].id,
          supplierId: this.state.supplierList[0].id

        })
      }
    })
  }
  del(row, index) {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "确定是否删除？",
      onOk: async () => {
        let res = await apiStockInLibraryDetailsRevokeDetail({
          id: row.id,
          dataType: row.dataType,
          goodsSkuId: row.goodsSkuId,
          count: row.count,
          inLibraryId: this.state.inLibraryId,
          dataId: row.dataId ? row.dataId : ''
        })
        if (res.code === 0) {
          let dataSource = this.state.dataSource
          dataSource.splice(index, 1)
          this.setState({
            searchDataSource: []
          }, () => {
            this.setState({
              searchDataSource: dataSource
            })
          })
          React.$message({
            type: 'success',
            content: res.codeMessage
          })
        } else {
          React.$message({
            type: 'warning',
            content: res.codeMessage
          })
        }
      }
    });
  }
  async getView() {
    let res = await apiStockInLibraryView({ id: this.state.id })
    if (res.code === 0) {
      await this.getGoodsList(res.data.libraryId)
      if (res.data.dataType === 5) {
        this.setState({
          isAdd: true
        })
      }
      let totalCount = null
      res.data.stockInLibraryDetailsVos.map((v, k) => {
        totalCount += v.count
        v.index = k + 1
        return totalCount
      })
      this.setState({
        isSave: true,
        details: res.data,
        dataSource: this.state.dataSource.concat(res.data.stockInLibraryDetailsVos),
        code: res.data.code,
        inLibraryId: res.data.id,
        libraryId: res.data.libraryId,
        status: res.data.status,
        dataType: res.data.dataType,
        dataId: res.data.dataId,
        searchDataSource: this.state.dataSource.concat(res.data.stockInLibraryDetailsVos),
      })
      this.FormRef.current.setFieldsValue({
        libraryId: res.data.libraryId,
        supplierId: res.data.supplierId,
        remark: res.data.remark ? res.data.remark : ''
      })
      if (res.data.status === 1 || (res.data.dataType !== 5 && res.data.dataType !== 1)) {
        let columns = this.state.columns
        columns.pop()
        this.setState({
          columns: []
        }, () => {
          this.setState({
            columns: columns
          })
        })
      }
    }
  }
  async getGoodsList(libraryId) {
    let res = await apiGetGoodsList({ libraryId, type: 1 })
    if (res.code === 0) {
      this.setState({
        goodsList: res.data,
      })
    }
  }
  selectFilter(input, option) {
    const materialIds = option.option.materialIds.toLowerCase().split(',')
    const result = option.children.toLowerCase().includes(input.toLowerCase()) || materialIds.includes(input.toLowerCase())
    return result
  }
  goodsChange(e, _row) {
    this.apiGetGoodsDetail(e)
  }
  async apiGetGoodsDetail(goodsId) {
    let res = await apiGetGoodsDetail({ goodsId, libraryId: this.state.libraryId })
    if (res.code === 0) {
      if (this.state.materialId) {
        let result = res.data.skuInfo.filter(item => item.materialId === this.state.materialId)
        this.setState({
          productSku: res.data,
          currentSku: result.length > 0 ? result[0] : res.data.skuInfo[0]
        })
      } else {
        this.setState({
          productSku: res.data,
          currentSku: res.data.skuInfo[0]
        })
      }
      this.addFormRef.current.setFieldsValue({
        price: res.data.skuInfo[0].price
      })
    }
  }
  // 获取供应商list
  async getSuppliers() {
    let res = await apiStockSupplierManageList()
    if (res.code === 0) {
      this.setState({
        supplierList: res.data
      })
    }
    return res
  }
  // 获取仓库list
  async getStores() {
    let res = await apiStockLibraryManageList()
    if (res.code === 0) {
      this.setState({
        storeList: res.data
      })
    }
    return res
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  triggerSkuTag(row) {
    this.setState({
      currentSku: row
    })
    this.addFormRef.current.setFieldsValue({
      price: row.price
    })
  }
  async onFinishAdd(values) {
    let { inLibraryId, currentSku, code } = this.state
    let res = await apiStockInLibraryDetailsAdd({
      inLibraryId: inLibraryId,
      goodsSkuId: currentSku.SKUId,//skuId
      dataType: 5,
      code: code,
      count: values.nowCount,//盘点库存
      unitPrice: (values.price * 100).toFixed(0), //入库价格
      beforeCount: currentSku.stock,//当前库存
    })
    if (res.code === 0) {
      message.success(res.codeMessage);
      this.reset()
      this.setState({
        dataSource: this.state.dataSource.concat(res.data),
        searchDataSource: this.state.dataSource.concat(res.data),
        isModalVisible: false
      })

    }
  }
  onFinishSearch() { }
  setSearchValue = (value) => {
    const { dataSource } = this.state
    let search = value.target.value.trim()
    if (search) {
      this.setState({
        searchDataSource: this.getSearchData(dataSource, search)
      })
    } else {
      this.setState({
        searchDataSource: this.state.dataSource
      })
    }
  }
  getSearchData(aim, searchVal) {
    let newArr = []
    for (var i = 0; i < aim.length; i++) {
      let value = aim[i].goodsName, value1 = aim[i].goodsSkuNo, value2 = aim[i].materialName
      if (value.includes(searchVal) || value1.includes(searchVal) || value2.includes(searchVal)) {
        newArr.push(aim[i]);//将值放入第二个数组
      }
    }
    return newArr
  }
  handleCancel() { }
  savePutInOrder = () => {
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '保存入库单后将不可修改，确定保存入库单吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        let values = this.FormRef.current.getFieldsValue()
        let res = await apiStockInLibraryAdd({
          libraryId: values.libraryId,
          supplierId: values.supplierId,
          remark: values.remark ? values.remark : ''
        })
        if (res.code === 0) {
          this.getGoodsList(values.libraryId)
          this.setState({
            isSave: true,
            isAdd: true,
            code: res.data.code,
            inLibraryId: res.data.id,
            libraryId: values.libraryId,
            dataType: res.data.dataType
          })
        }
      }
    });
  }
  reset() {
    this.addFormRef.current.setFieldsValue({
      nowCount: null,
      goodsId: '',
      dataType: '',
      unitPrice: '',
      price: ''
    })
    this.setState({
      productSku: {},
      currentSku: {}
    })
  }
  execute() {
    React.$confirm({
      title: "提示",
      type: 'warning',
      content: "是否确定操作？",
      onOk: async () => {
        let res = await apiStockInLibraryDetailsRevokeConfirmInLibrary({
          "dataId": this.state.dataId,
          "dataType": this.state.dataType,
          "id": this.state.inLibraryId,
          "libraryId": this.state.libraryId,
          "stockInLibraryDetails": this.state.dataSource
        })
        if (res.code === 0) {
          React.$message({
            type: 'success',
            content: res.codeMessage
          })
          setTimeout(() => {
            this.props.history.go(-1)
          }, 2000);
        }
      }
    })
  }
  exportGoodsDetail() {
    const th_arr = [
      {
        title: `入库单详情(单号：${this.state.code})`,
        prop: '',
        children: [
          {
            title: '序号',
            prop: 'index',
          },
          {
            title: '商品名称',
            prop: 'goodsName',
          },
          {
            title: '物料名称',
            prop: 'materialName',
          },
          {
            title: '规格',
            prop: 'goodsSkuName',
          },
          {
            title: "物料ID",
            prop: "goodsSkuNo",
          },
          {
            title: '入库前库存',
            prop: 'beforeCount',
            valueType: 'number'
          },
          {
            title: '入库数量',
            prop: 'count',
            valueType: 'number'
          },
          {
            title: '操作时间',
            prop: 'createTime',
          },
          {
            title: '操作人',
            prop: 'memberName',
          }
        ]
      },

    ]
    let tb_arr = this.state.dataSource
    exportSheetTable({ fileName: `入库单详情(单号：${this.state.code})`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
  }
  onBlur = (materialId) => {
    this.setState({
      materialId
    })
  }
  //打印
  billPrint = async () => {
    const res = await apiPrintInLibraryOrder({ inLibraryId: this.state.id })
    if (res.code === 0) {
      const data = res.data.stockInLibraryPrintDetailVos
      let resultData = [], countTotal = 0, payTotal = 0
      data.forEach((item, index) => {
        item.sort = index + 1
        countTotal += item.count
        resultData.push(item)
        if (index === data.length - 1) {
          resultData.push({
            materialId: '合计',
            count: countTotal,
          })
        }
      })
      let infos = []
      if (this.state.dataType === 1) {
        infos = [
          { label: '单据编号', value: res.data.inLibraryCode },
          { label: '单据日期', value: res.data.createTime },
          { label: '入库仓库', value: res.data.stockName },
          { label: '采购单号', value: res.data.purchaseNoteCode },
          { label: '供应商', value: res.data.supplierName },
        ]
      } else {
        infos = [
          { label: '单据编号', value: res.data.inLibraryCode },
          { label: '单据日期', value: res.data.createTime },
          { label: '退货仓库', value: res.data.stockName },
          { label: '物流单号', value: res.data.returnCourierNo },
          { label: '退单号', value: res.data.returnCode },
          { label: '订单号', value: res.data.orderCode },
        ]
      }
      toPrintTool(
        [
          {
            th: [
              { label: '序号', value: 'sort', width: '5%' },
              { label: '物料编码', value: 'materialId', width: '12%' },
              { label: '物料名称', value: 'materialName', width: '30%', align: 'start' },
              { label: '规格', value: 'skuName', width: '13%' },
              { label: '描述', value: 'skuDescription', width: '10%' },
              { label: '数量', value: 'count', width: '5%' },
              { label: '备注', value: 'remark', width: '25%', align: 'start' },
            ],
            title: res.data.tableName,
            data: resultData,
            infos: infos,
            remark: res.data.libraryRemark ?? '',
            tfoot: {
              '审核人': '',
              '审核日期': '',
              '仓管员': '',
              '创建人': '',
            }
          }
        ]
      )
    }
  }
  remarkChange = async () => {
    const { id } = this.state
    let remark = this.FormRef.current.getFieldsValue().remark
    let res = await apiPostChangeRemark({ inLibraryId: id, remark })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改备注成功'
      })
    }
  }

  render() {
    let { columns, supplierList, goodsList, status, searchDataSource, details, libraryId, storeList, productSku, currentSku, dataSource, isModalVisible, isSave, isAdd } = this.state
    return (
      <div className="p-layout-box">
        <GoBack history={this.props.history} title="新增入库管理" />
        <Form layout={'inline'} ref={this.FormRef} onFinish={this.onFinishSearch} style={{ marginBottom: 12, marginTop: 12 }}>
          <Form.Item name={"libraryId"}>
            <Select disabled={libraryId ? true : false} style={{ width: 200 }} placeholder={"入库仓库"}>
              {
                storeList.map(item => {
                  return <Option value={item.id}>{item.name}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name={"supplierId"}>
            <Select disabled={libraryId ? true : false} style={{ width: 200 }} placeholder={"供应商"}>
              {
                supplierList.map(item => {
                  return <Option value={item.id}>{item.supplierName}</Option>
                })
              }
            </Select>
          </Form.Item>
          <Form.Item name={"remark"}>
            <TextArea disabled={status !== 1 ? false : true} autoSize={false} rows={1} style={{ width: 340 }} maxLength={60} placeholder={"备注"} />
          </Form.Item>
          <Space>
            {status !== 1 && status !== null ? <TheButton size="middle" type="default" onClick={() => this.remarkChange()} >修改</TheButton> : null}
            <Search
              placeholder="请输入物料名称/物料ID"
              onChange={(e) => this.setSearchValue(e)}
              style={{
                width: 200,
              }}
              allowClear
            />
          </Space>
          <Space style={{ marginLeft: 12 }}>
            <TheButton onClick={() => this.exportGoodsDetail()} haspermi={['storage:putIn:exportGoodsDetail']} size="middle" type="default">导出</TheButton>
            {
              details.finishTime == null ? null : <TheButton haspermi={['storage:outPut:print']} onClick={this.billPrint} size="middle" type="default">打印</TheButton>
            }
          </Space>
        </Form>
        {
          status !== 1 ? <div style={{ marginBottom: 12 }}>
            {
              !isSave ?
                <TheButton haspermi={['storage:putIn:savePutInOrder']} onClick={() => this.savePutInOrder()} size="middle" type="primary">保存入库单</TheButton>
                :
                isAdd ?
                  <div>
                    <TheButton onClick={() => this.setState({ isModalVisible: true })} haspermi={['storage:putIn:addInfo']} size="middle" type="primary">添加商品</TheButton>
                  </div> : null
            }
          </div> : null
        }
        <Table
          scroll={{ x: "max-content", y: '63vh' }}
          columns={columns}
          bordered
          dataSource={searchDataSource}
          summary={(res) => (
            <Table.Summary fixed>
              <Table.Summary.Row >
                <Table.Summary.Cell index={0}></Table.Summary.Cell>
                <Table.Summary.Cell index={1} align='center'>合计</Table.Summary.Cell>
                <Table.Summary.Cell index={2} colSpan={4}></Table.Summary.Cell>
                <Table.Summary.Cell index={5} colSpan={1} align='center'>{res.reduce((prev, cur) => prev + cur.count, 0)}</Table.Summary.Cell>
                <Table.Summary.Cell index={4} colSpan={5}></Table.Summary.Cell>
              </Table.Summary.Row>
            </Table.Summary>
          )}
        />
        {
          status !== 1 ? <div style={{ textAlign: 'center', marginTop: 12 }}>
            {
              dataSource.length > 0 &&
              <TheButton type="primary" size='middle' haspermi={['storage:putIn:execute']} onClick={() => this.execute(1)}>提交</TheButton>
            }
          </div> : null
        }

        <Modal title="新增" visible={isModalVisible} width="40%"
          onCancel={() => {
            this.setState({ isModalVisible: false })
            Modal.destroyAll()
          }}
          footer={null}
        >
          <Form
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 16,
            }}
            ref={this.addFormRef}
            onFinish={(values) => this.onFinishAdd(values)}
          >
            <Row>
              <Col span={24}>
                <Form.Item
                  label="选择商品"
                  name="goodsId"
                  rules={[
                    {
                      required: true,
                      message: '请选择商品!',
                    },
                  ]}
                >
                  <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) => this.selectFilter(input, option)}
                    style={{
                      width: '100%',
                    }}
                    onSearch={(e) => this.onBlur(e)}
                    onSelect={(e, obj) => this.goodsChange(e, obj)}
                    placeholder="请选择商品"
                  >
                    {
                      goodsList.map(item => <Option option={item} key={item.goodsId} value={item.goodsId}>{item.goodsName}</Option>)
                    }
                  </Select>
                </Form.Item >
              </Col>
              <Col>
                {
                  productSku.hasOwnProperty('goodsInfo') ?
                    <Form.Item
                      wrapperCol={{
                        offset: 4,
                        span: 16,
                      }}
                    >
                      <div className='goodsDesc'>
                        <div className='info'>
                          <img src={currentSku.imageFile ? currentSku.imageFile.split(',')[0] : ''} alt="商品图片" className='goodsImg' />
                          <div className="goodsInfo">
                            <div className='name'>{productSku.goodsInfo.goodsName}</div>
                            <div className='stock' >
                              物料名称：{currentSku.materialName}
                            </div>
                            <div className='stock' >
                              物料ID：{currentSku.materialId}
                            </div>
                            <div className='stock' >
                              可售库存：{currentSku.stock}
                            </div>
                            <div className='stock' >
                              待出库存：{currentSku.waiteOutCount}
                            </div>
                            <div className='stock' >
                              实际库存：{currentSku.realStock}
                            </div>
                          </div>
                        </div>
                        <div className='goodsSku'>
                          {
                            productSku.skuInfo.map(item =>
                              <Tag className='tag' key={item.SKUId} color={item.SKUId === currentSku.SKUId ? "cyan" : ''} onClick={() => this.triggerSkuTag(item)}>
                                {item.skuAttribute.map(item2 => item2.value).join(',')}
                              </Tag>
                            )
                          }

                        </div>
                      </div>
                    </Form.Item> : null
                }
              </Col>
              <Col span={24}>
                <Form.Item
                  label="入库数"
                  name="nowCount"
                  rules={[
                    {
                      required: true,
                      message: '请输入!',
                    },
                  ]}
                >
                  <InputNumber style={{
                  }} precision={0} min={0} />
                </Form.Item>
              </Col>
              <Col span={24}>
                <Form.Item
                  label="入库价格"
                  name="price"
                  rules={[
                    {
                      required: true,
                      message: '请输入!',
                    },
                  ]}
                  style={{ display: 'none' }}
                >
                  <InputNumber style={{
                  }} precision={2} min={0} disabled />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item wrapperCol={{
                  offset: 8,
                  span: 16,
                }}>
                  <Space size="small" style={{ marginLeft: 10 }}>
                    <Button type="default" onClick={() => this.reset()}>
                      重置
                    </Button>
                    <Button type="primary" htmlType="submit">
                      确定
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}
